from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
import random
import logging
from rest_framework import status

# from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms_code
from . import constants


logger = logging.getLogger('django')


class SMSCodeView(APIView):

    def get(self, request, mobile):

        redis_conn = get_redis_connection('verify_codes')

        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:

            return Response({'message': '发送消息过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        sms_code = '%06d' % random.randint(0, 999999)

        print(sms_code)

        logger.debug(sms_code)

        pl = redis_conn.pipeline()

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        # redis_conn.setex('send_%s' % mobile, 300, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, constants.SMS_CODE_TEMP_ID)

        pl.execute()

        send_sms_code.delay(mobile, sms_code)

        return Response({'message': 'OK'})
